package com.aiyige.utils;

import android.text.TextUtils;

import com.aiyige.base.eventbus.EventBalanceChanged;
import com.aiyige.model.User;
import com.aiyige.model.User.MineBackup;
import com.aiyige.model.User.MoreBackup;
import com.aiyige.model.User.SlideImage;
import com.aiyige.model.User.StatisticsBackup;
import com.aiyige.model.User.ThirdOauthBackup;
import com.aiyige.model.User.TokenBackup;
import com.aiyige.model.tag.Tag;
import com.aiyige.setup.util.SetupUtil;
import com.alibaba.fastjson.JSON;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nimlib.sdk.auth.LoginInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Created by zhuyakun on 2017/9/27.
 */

public class AccountUtil {
    private static final String PREF_KEY_ACCOUNT = "com.aiyige.pref.PREF_KEY_ACCOUNT";
    private static final String PREF_KEY_NIM_LOGIN = "com.aiyige.pref.PREF_KEY_NIM_LOGIN";
    private static final String PREF_KEY_WIFI_REMIND_TIME = "com.aiyige.pref.PREF_KEY_WIFI_REMIND_TIME";
    private static User user = null;

    public static boolean isNimLogin() {
        return PreferenceUtil.getBoolean(PREF_KEY_NIM_LOGIN, false);
    }

    public static void setNimLogin(boolean nimLogin) {
        PreferenceUtil.putBoolean(PREF_KEY_NIM_LOGIN, nimLogin);
    }

    public static void setWIFIRemindTime() {
        PreferenceUtil.putString(PREF_KEY_WIFI_REMIND_TIME, TimeUtils.dateToYYYYMMDD(System.currentTimeMillis()));
    }

    public static boolean isWIFIRemind() {
        String lastTime= PreferenceUtil.getString(PREF_KEY_WIFI_REMIND_TIME, null);
        if (TextUtils.isEmpty(lastTime)) {
            return true;
        }
        String currentDate = TimeUtils.dateToYYYYMMDD(System.currentTimeMillis());
        return !currentDate.equals(lastTime);
    }


    public synchronized static User getCurrentUser() {
        if (user != null) {
            return user;
        }
        try {
            String sessionJson = PreferenceUtil.getString(PREF_KEY_ACCOUNT, "");
            if (TextUtils.isEmpty(sessionJson) || sessionJson.equals("null")) {
                throw new Exception("NO_SESSION");
            }
            user = JSON.parseObject(PreferenceUtil.getString(PREF_KEY_ACCOUNT, ""), User.class);
        } catch (Exception e) {
            user = new User();
            PreferenceUtil.putString(PREF_KEY_ACCOUNT, JSON.toJSONString(user));
        }
        return user;
    }

    public synchronized static void updateCurrentUser(User newUser) {
        user = new User();
        if (User.TOKEN_TYPE_GUEST.equals(newUser.getAccessToken().getToken_type())) {
            TokenBackup tokenBackup = new TokenBackup();
            tokenBackup.setGuestAccessTokenBackup(newUser.getAccessToken().getAccess_token());
            tokenBackup.setGuestRefreshTokenBackup(newUser.getAccessToken().getRefresh_token());
            tokenBackup.setAccess_token(newUser.getAccessToken().getAccess_token());
            tokenBackup.setToken_type(newUser.getAccessToken().getToken_type());
            tokenBackup.setRefresh_token(newUser.getAccessToken().getRefresh_token());
            tokenBackup.setExpires_in(newUser.getAccessToken().getExpires_in());
            tokenBackup.setScope(newUser.getAccessToken().getScope());
            user.setRouter("");
            user.setLoginTimestamp(System.currentTimeMillis());
            user.setAccessToken(tokenBackup);
            user.setId("");
            user.setAccount("");
            user.setPassword("");
            user.setSalt("");
            user.setAvatar("");
            user.setMiniAvatar("");
            user.setMobile("");
            user.setMobileVerified(0);
            user.setLevel(0);
            user.setStatus(0);
            user.setCreateTime(0L);
            user.setUpdateTime(0L);
            user.setToken("");
            user.setNewUser(false);
            user.setThirdOauthBackup(new ThirdOauthBackup());
            user.setSlideBackup(new ArrayList<SlideImage>());
            user.setMoreBackup(new MoreBackup());
            user.setStatisticsBackup(new StatisticsBackup());
            user.setMineBackup(new MineBackup());
            user.setChannel(Tag.newBuilder().groupType(SetupUtil.GROUP_TYPE_CHANNEL).build());
            user.setColumnBackup(new LinkedList<Tag>());
            user.setAvocation(new LinkedList<Tag>());
            user.setWalletPassword(new User.WalletPassword());
            user.setUserAccidPassword(new User.IMBackup());
        } else {
            TokenBackup tokenBackup = new TokenBackup();
            tokenBackup.setAccess_token(newUser.getAccessToken().getAccess_token());
            tokenBackup.setToken_type(newUser.getAccessToken().getToken_type());
            tokenBackup.setRefresh_token(newUser.getAccessToken().getRefresh_token());
            tokenBackup.setExpires_in(newUser.getAccessToken().getExpires_in());
            tokenBackup.setScope(newUser.getAccessToken().getScope());
            user.setLoginTimestamp(System.currentTimeMillis());
            user.setAccessToken(tokenBackup);
            user.setId(newUser.getId());
            user.setRouter(newUser.getRouter());
            user.setAccount(newUser.getAccount());
            user.setPassword(newUser.getPassword());
            user.setSalt(newUser.getSalt());
            user.setAvatar(newUser.getAvatar());
            user.setMiniAvatar(newUser.getMiniAvatar());
            user.setMobile(newUser.getMobile());
            user.setMobileVerified(newUser.getMobileVerified());
            user.setLevel(newUser.getLevel());
            user.setStatus(newUser.getStatus());
            user.setCreateTime(newUser.getCreateTime());
            user.setUpdateTime(newUser.getUpdateTime());
            user.setToken(newUser.getToken());
            user.setThirdOauthBackup(newUser.getThirdOauthBackup());
            user.setSlideBackup(newUser.getSlideBackup());
            user.setMoreBackup(newUser.getMoreBackup());
            user.setStatisticsBackup(newUser.getStatisticsBackup());
            user.setMineBackup(newUser.getMineBackup());
            user.setChannel(newUser.getChannel());
            user.setColumnBackup(newUser.getColumnBackup());
            user.setAvocation(newUser.getAvocation());
            user.setNewUser(newUser.isNewUser());
            user.setWalletPassword(newUser.getWalletPassword());
            user.setHasWalletPassword(newUser.isHasWalletPassword());
            user.setUserAccidPassword(newUser.getUserAccidPassword());

        }
        PreferenceUtil.putString(PREF_KEY_ACCOUNT, JSON.toJSONString(user));
    }

    public synchronized static void clearCurrentUser() {
        User oldUser = user;
        user = new User();
        user.getAccessToken().setAccess_token(oldUser.getAccessToken().getGuestAccessTokenBackup());
        user.getAccessToken().setToken_type(User.TOKEN_TYPE_GUEST);
        PreferenceUtil.putString(PREF_KEY_ACCOUNT, JSON.toJSONString(user));
    }

    public synchronized static boolean isLogin() {
        User user = getCurrentUser();
        if (User.TOKEN_TYPE_USER.equals(user.getAccessToken().getToken_type()) && !TextUtils.isEmpty(user.getAccessToken().getAccess_token()) && !TextUtils.isEmpty(user.getAccessToken().getRefresh_token())) {
            return true;
        } else {
            return false;
        }
    }

    public synchronized static void updateBalance(double balance) {
        User user = getCurrentUser();
        if (user != null && user.getStatisticsBackup() != null) {
            user.getStatisticsBackup().setPurseBalance(balance);
            EventBus.getDefault().post(new EventBalanceChanged());
        }
    }


    public synchronized static double getBalance() {
        User user = getCurrentUser();
        if (user != null && user.getStatisticsBackup() != null) {
            return user.getStatisticsBackup().getPurseBalance() > 0 ? user.getStatisticsBackup().getPurseBalance():0;
        }
        return 0;
    }



    public synchronized static boolean isGuestLogin() {
        User user = getCurrentUser();
        if (User.TOKEN_TYPE_GUEST.equals(user.getAccessToken().getToken_type()) && !TextUtils.isEmpty(user.getAccessToken().getAccess_token())) {
            return true;
        } else {
            return false;
        }
    }

    public synchronized static boolean hasWalletPassword() {
        User user = getCurrentUser();
        if (user != null) {
            return user.isHasWalletPassword();
        }
        return false;
    }

    public synchronized static User.IMBackup getIMbackup() {
        User user = getCurrentUser();
        if (user != null) {
            return user.getUserAccidPassword();
        }
        return null;
    }

    public synchronized static String getMobile() {
        User user = getCurrentUser();
        if (user != null) {
            return user.getMobile();
        }
        return null;
    }

    public synchronized static LoginInfo getLoginInfo() {
        if (null != getIMbackup() && !StringUtil.isEmpty(getIMbackup().getAccid())) {
            return new LoginInfo(getIMbackup().getAccid(), getIMbackup().getToken());
        } else {
            return null;
        }

    }


}
